import { load } from "/admin/util/LoadView.js";
load('newslist');
let previewModal = new bootstrap.Modal(document.getElementById('previewModal'))//modal的实例化
let deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'))

let category = ["最新动态", "典型案例", "通知公告"]
let news = [] //存放新闻列表
let newsid = 0

let render = async function () {
    news = await fetch("http://localhost:3000/news").then(res => res.json())
    newslistbody.innerHTML = news.map(item => `
    <tr>
        <th scope="row">${item.title}</th>
        <td>${category[item.category]}</td>
        <td>
            <button type="button" data-id="${item.id}" class="btn btn-success btn-sm btn-preview">预览</button>
            <button type="button" data-id="${item.id}" class="btn btn-primary btn-sm btn-edit">更新</button>
            <button type="button" data-id="${item.id}" class="btn btn-danger btn-sm btn-delete">删除</button>
        
        </td>
        </tr>    
    `).join('')
}
document.querySelector('#newslistbody').onclick = function (evt) {
    newsid = evt.target.dataset.id
    if (evt.target.className.includes('btn-preview')) {
        previewModal.toggle();
        let n = news.filter(item => item.id == newsid)
        // console.log(n)
        newsTitleModalLabel.innerHTML = `${n[0].title}`
        newsContentModalLabel.innerHTML = `${n[0].content}`
    } else if (evt.target.className.includes('btn-edit')) {
        location.href = `/admin/views/newsManage/editNews/index.html?id=${newsid}`
    } else if (evt.target.className.includes('btn-delete')) {
        deleteModal.toggle();
    }
}
deleteConfirm.onclick = async function () {
    await fetch(`http://localhost:3000/news/${newsid}`,{
        method:'DELETE'
    }).then(res => res.json())
    deleteModal.toggle();
    render()
}
render()